<template>
    <div class="adminRole">
        <el-form ref="formRef" :inline="true" :model="form" class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]">
            <el-form-item label="交管名称：" prop="name">
                <el-input v-model="form.name" placeholder="请输入交管名称" clearable class="!w-[200px]" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="useRenderIcon(Search)" :loading="loading" @click="onSearch">
                    搜索
                </el-button>
                <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
                    重置
                </el-button>
            </el-form-item>
        </el-form>

        <div class="center_bg">
            <PureTableBar title="交管管理" :columns="columns" @refresh="onSearch" style="width: 410px">
                <template #buttons>
                    <el-button type="success" size="small" :icon="useRenderIcon(AddFill)" @click="addCross">
                        交管设置
                    </el-button>
                    <el-tooltip effect="dark" :content="agvCrossSwitch ? '显示全部交管' : '显示有排队车辆的交管'" placement="top">
                        <el-icon class="lookAgv" :size="20" @click="crossSearch">
                            <Van v-show="!agvCrossSwitch" />
                            <Guide v-show="agvCrossSwitch" />
                        </el-icon>
                    </el-tooltip>
                    <!-- <el-button type="primary" size="small" :icon="useRenderIcon(AddFill)" @click="openDialog()">
            新增交管
          </el-button> -->
                </template>
                <template v-slot="{ size, dynamicColumns }">
                    <pure-table ref="tableRef" adaptive :default-expand-all="expandOpen" align-whole="center"
                        size="small" border showOverflowTooltip table-layout="auto" :loading="loading" :data="dataList"
                        :columns="dynamicColumns" :pagination="pagination" :paginationSmall="true" :header-cell-style="{
                            background: 'var(--el-fill-color-light)',
                            color: 'var(--el-text-color-primary)'
                        }" @page-size-change="handleSizeChange" @page-current-change="handleCurrentChange">
                        <template #expand="{ row }">
                            <ul class="table_expand">
                                <li class="station">
                                    <div class="title">
                                        <span>站点集合：</span>
                                        <el-icon :size="15" @click="contract">
                                            <ArrowDown v-show="isContract" />
                                            <ArrowUp v-show="!isContract" />
                                        </el-icon>
                                    </div>
                                    <div :class="{ stationArr: !isContract }">
                                        <el-tag size="small" type="success" v-for="v in row.stationNameList" :key="v.id"
                                            style="margin: 5px 5px">
                                            {{ v }}
                                        </el-tag>
                                    </div>
                                </li>
                                <li>
                                    <span>排队车辆：</span>
                                    <!-- type="primary" -->
                                    <el-tag size="small" type="success" style="margin: 5px 5px" v-for="v in pureMap.scoketData.CrossMsgData?.find(j => {
                                        return j.CrossId === row.id;
                                    })?.AgvList" :key="v.Id" closable @close="agvClose(row, v)">
                                        {{ v.Name }}
                                    </el-tag>
                                </li>
                                <li v-if="row.type === 3">
                                    <el-button type="primary" size="small" @click="releaseTrafficControl(row)">
                                        释放交管
                                    </el-button>
                                </li>
                            </ul>
                        </template>
                        <template #operation="{ row }">
                            <el-button class="reset-margin" link type="primary" size="small" @click="crossUp(row.id)">
                                编辑
                            </el-button>
                            <el-button class="reset-margin" link type="danger" size="small" style="margin-left: 0px"
                                @click="deleteCross(row)">
                                删除
                            </el-button>
                        </template>
                    </pure-table>
                </template>
            </PureTableBar>

            <!-- 设置交管地图 -->
            <div class="mapDraw mt-2">
                <div class="mapCross">
                    <div class="mapCorrd">
                        <p>x:{{ mouseCorrd.x }},y:{{ mouseCorrd.y }}</p>
                    </div>
                    <!-- 交管提示 -->
                    <div class="crossClass">
                        <ul>
                            <li>巷道区域：<span></span></li>
                            <li>唯一区域：<span></span></li>
                            <li>公共区域：<span></span></li>
                            <li>穿行区域：<span></span></li>
                            <li>多车交管：<span></span></li>
                        </ul>
                    </div>
                    <div id="canvasMap" ref="map"></div>
                </div>
            </div>
        </div>

        <!-- 抽屉 -->
        <el-drawer v-model="pureMap.crossSwitch" :title="isUpdate ? '修改交管区域' : '新增交管区域'" direction="ltr" size="400px"
            :close-on-click-modal="true" :modal="false" modal-class="modalCross">
            <el-form-item label="隐藏其余交管">
                <el-switch v-model="isSwatch" width="60"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" inline-prompt
                    :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" />
            </el-form-item>
            <el-alert title="可以通过双击右侧地图来添加交管坐标" type="warning" center :closable="false" style="margin-bottom: 20px" />
            <!-- <crossForm :formInline="formInline" :isUpdate="isUpdate" ></crossForm> -->
            <crossForm :isUpdate="isUpdate" ref="crossRef"></crossForm>
        </el-drawer>
    </div>
</template>

<script lang="ts" setup>
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useDept } from "./utils/hook";
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import { getCross } from "@/utils/api/dispatch/cross";
import mapCross from "./components/mapCross.vue";
import {
    initKonvaStage,
    mouseCorrd,
    stage
} from "@/views/home/components/dxfMap";
import { readFile } from "@/views/home/components/readFile";
import { useMapStoreHook } from "@/store/modules/map";
import crossForm from "./crossForm.vue";
import { websock } from "@/utils/webScoket";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { delCross } from "@/utils/api/dispatch/cross";
import { Van, Guide, ArrowUp, ArrowDown } from "@element-plus/icons-vue";
import {
    hideCross,
    showCross,
    getCross1
} from "@/views/home/components/dxfMap";

// iconify-icons
import AddFill from "@iconify-icons/ri/add-circle-line";
import EditPen from "@iconify-icons/ep/edit-pen";
import outlineDelete from "@iconify-icons/ic/outline-delete";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";

const formRef = ref();
const map = ref();
const pureMap = useMapStoreHook();
var isUpdate = ref(false);
const crossRef = ref(null);
var isContract = ref(false);
var crossList: any = ref([]);

// 交管颜色
const crossColor = new Map([
    [1, "rgba(126, 192, 80, 1)"],
    [2, "rgba(52, 120, 198, 1)"],
    [3, "#FF00FF"],
    [4, '#b76f40'],
    [5, '#00FFFF']
]);

// 隐藏交管开关
const isSwatch = ref(false);
watch(
    () => isSwatch.value,
    newValue => {
        if (newValue) {
            if (isUpdate.value) {
                hideCross(dataList.value, pureMap.targetCross.attrs.id);
            } else {
                hideCross(dataList.value);
            }
        } else {
            showCross(dataList.value);
        }
    },
    { deep: true }
);

// 监听抽屉开关，当抽屉关闭时刷新列表数据
watch(
    () => pureMap.crossSwitch,
    newValue => {
        if (!newValue) {
            // 检查 pureMap.targetCross.attrs 是否为 undefined，如果是则返回 false
            if (pureMap.targetCross.attrs === undefined) return false;
            // console.log('选中的', pureMap.targetCross.attrs);
            // const color = pureMap.targetCross.attrs.type === 1 ? 'rgba(126, 192, 80, 1)' : 'rgba(52, 120, 198, 1)'
            const color = crossColor.get(pureMap.targetCross.attrs.type);
            // 遍历 pureMap.targetCross 的子元素
            pureMap.targetCross.children.forEach(v => {
                // 如果子元素是圆形，则填充颜色
                if (v.name() === "circle") {
                    v.fill(color);
                } else {
                    // 否则，设置边框颜色
                    v.stroke(color);
                }
            });
            nextTick(() => {
                // 调用 onSearch 函数，可能是为了刷新或重新搜索相关数据
                onSearch();
                // 重置表单数据
                formRef.value.resetFields();
                // stage.destroy();
                // infoMap()
            });
            // 检查 isSwatch 的值，如果为 true，则显示交叉点并重置 isSwatch 为 false
            if (isSwatch.value) {
                showCross(dataList.value);
                isSwatch.value = false;
            }
        }
    }
);

// 车辆移除交管
function agvClose(row, agv) {
    ElMessageBox.confirm(`是否确认将${agv.Name}移出${row.name}交管?`, "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        center: true
    })
        .then(() => {
            websock.send(
                JSON.stringify({ type: "移出交管", data: row.id, agvid: agv.Id })
            );
            message(`提交成功`, { type: "success" });
        })
        .catch(() => { });
}

// 公共区域释放交管
function releaseTrafficControl(row) {
    ElMessageBox.confirm(`是否确认释放名称为${row.name}的公共区域交管?`, "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        center: true
    })
        .then(() => {
            websock.send(
                JSON.stringify({ type: "释放公共区域交管", data: row.id, })
            );
            message(`提交成功`, { type: "success" });
        })
        .catch(() => { });
}

// 交管新增
function addCross() {
    // hideCross,showCross()
    // 调用 pureMap 对象的 operateDrawer 方法，传入 true 参数，可能是打开某个抽屉组件
    pureMap.operateDrawer(true);    
    // 将 isUpdate 的值设置为 false，可能是表示当前不是更新状态
    isUpdate.value = false;
    // 检查 crossRef.value 是否存在，如果存在则调用其 resetForm 方法，并传入 getRef 方法的返回值
    // 这可能是重置某个表单组件的状态
    crossRef.value?.resetForm(crossRef.value.getRef());
}

// 交管编辑
function crossUp(id: number) {
    isUpdate.value = true;
    pureMap.$patch({
        crossSwitch: true
    });

    nextTick(() => {
        crossRef.value.crossUpdate(id);
    });
}

// 删除交管
function deleteCross(row) {
    ElMessageBox.confirm(`是否确认删除名称为${row.name}的数据项?`, "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        center: true
    })
        .then(() => {
            delCross(row.id).then(res => {
                if (res.Code === 0) {
                    pureMap.stageKonva.find(`.cross-${row.name}`)[0].destroy();
                    message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
                    onSearch();
                }
            });
        })
        .catch(() => { });
}

// 站点集合缩放
function contract() {
    isContract.value = !isContract.value;
}

// async function crossUpdate(id: number) {
//   let { Content } = await getCross(id)
//   formInline.value = Content
//   formInline.value.stationids = formInline.value?.stationids?.split(',').map(v=>{return Number(v)})

//   for(let key in pureMap.crossDetail){
//     pureMap.$patch((state)=>{
//       state.crossDetail[key] = Content[key]
//     })
//   }
//   isUpdate.value = true

//   pureMap.getCross(pureMap.stageKonva.find(`.cross-${pureMap.crossDetail.name}`)[0])

//   pureMap.$patch({
//     crossSwitch: true
//   })
// }

// // 路段编辑
// async function crossUpdate(id: number) {
//   let { Content } = await getCross(id)
//   openDialog('编辑', Content)
// }

async function infoMap() {
    const data = await readFile();
    initKonvaStage("canvasMap", map, data, true);

    // 监听舞台（stage）上的双击事件
    stage.on("dblclick", function (e) {
        // 检查crossSwitch标志，如果为true则直接返回，不执行后续操作
        if (pureMap.crossSwitch) return false;
        // console.log(e.target);

        const id = e.target.parent?.id();
        if (id) {
            // 将获取到的id转换为数字类型，并调用crossUp函数进行处理
            crossUp(Number(id));
        } else {
            addCross();
        }
    });
}

onMounted(async () => {
    infoMap()
});

// 在组件卸载时执行的钩子函数
onUnmounted(() => {
    // 调用 pureMap 对象的 clearCross 方法，清除地图上的交叉点或标记
    pureMap.clearCross();
});

const {
    columns,
    loading,
    dataList,
    openDialog,
    handleDelete,
    form,
    onSearch,
    resetForm,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    agvCrossSwitch,
    crossSearch,
    expandOpen
} = useDept();
</script>

<style lang="scss" scoped>
.search-form {
    :deep(.el-form-item) {
        margin-bottom: 12px;
    }
}

.table_expand {
    padding-left: 15px;

    li {
        &:nth-last-child(1) {
            margin-top: 10px;
        }
    }
}

.center_bg {
    display: flex;
    justify-content: space-between;
    height: 100%;
}

.mapDraw {
    width: calc(100% - 420px);
    background: white;

    .mapCross {
        position: relative;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, rgba(62, 61, 61, 0.4) 2%, transparent 0%) 0 0,
            linear-gradient(180deg, transparent 99%, rgba(62, 61, 61, 0.4) 1%) 0 0;
        background-size: 50px 50px;
        background-color: #001529;
    }

    .crossClass {
        position: absolute;
        top: 5px;
        right: 5px;
        z-index: 99;

        li {
            color: white;
            font-size: 12px;
            margin-bottom: 5px;

            &:nth-child(1) {
                span {
                    background: rgba(52, 120, 198, 1);
                }
            }

            &:nth-child(2) {
                span {
                    background: rgba(126, 192, 80, 1);
                }
            }

            &:nth-child(3) {
                span {
                    background: #FF00FF;
                }
            }

            &:nth-child(4) {
                span {
                    background: #b76f40;
                }
            }

            &:nth-child(5) {
                span {
                    background: #00FFFF;
                }
            }

            span {
                display: inline-block;
                width: 40px;
                height: 15px;
                vertical-align: middle;
            }
        }
    }

    #canvasMap {
        width: 100%;
        height: 100%;
    }
}

.lookAgv {
    height: 23px;
    margin-left: 15px;
    vertical-align: bottom;

    &:hover {
        cursor: pointer;
    }
}

.station {
    .title {
        padding-right: 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .el-icon:hover {
        cursor: pointer;
    }

    .stationArr {
        width: 380px;
        height: 30px;
        /* 设置元素内容的溢出行为为隐藏，即超出元素边界的内容将被裁剪 */
        overflow: hidden;
        /* 设置元素内的文本不换行，保持在一行内显示 */
        white-space: nowrap;
        /* 当文本内容溢出时，使用省略号表示被裁剪的部分 */
        text-overflow: ellipsis;
    }
}

// 分页样式穿透
:deep(.el-pagination) {
    display: flex !important;
    justify-content: flex-start !important;
    overflow-x: auto !important;
}
</style>
